<template>
  <div class="chat-container">
    <div class="chat-card">
      <transition name="scale-fade" mode="out-in">
        <!-- 开始界面 -->
        <div v-if="!started" key="start" class="start-section">
          <h1 class="title-glow">法律知识对话测评</h1>
          <button @click="startExam" class="neon-btn" :disabled="isLoading">
            <i v-if="isLoading" class="fas fa-spinner fa-spin"></i>
            <span class="neon-text"
              >🚀 {{ isLoading ? "题目加载中..." : "开始挑战" }}</span
            >
            <div class="neon-border"></div>
          </button>
        </div>

        <!-- 对话界面 -->
        <div v-else key="chat" class="dialog-container">
          <div class="dialog-scroll">
            <transition-group name="chat-fade" tag="div">
              <!-- 对话消息 -->
              <div
                v-for="(msg, index) in chatHistory"
                :key="index"
                class="chat-bubble"
                :class="{ 'user-bubble': msg.isUser }"
              >
                <div class="avatar">
                  <i
                    :class="msg.isUser ? 'fas fa-user' : 'fas fa-balance-scale'"
                  ></i>
                </div>
                <div class="bubble" v-html="msg.content"></div>
                <!-- <div class="bubble">
                  {{ msg.content }}
                  <div class="message-mark">{{ msg.isUser ? "💡" : "❓" }}</div>
                </div> -->
              </div>
            </transition-group>
          </div>

          <!-- 输入区域 -->
          <div class="input-area" v-if="currentStep < 2">
            <div class="input-group">
              <textarea
                v-model="currentAnswer"
                placeholder="请输入您的回答..."
                rows="2"
                @keyup.enter.exact="submitAnswer"
              ></textarea>
              <button
                @click="submitAnswer"
                class="send-btn"
                :disabled="isSubmitting"
              >
                <i class="fas fa-paper-plane"></i>
                {{ isSubmitting ? "提交中..." : "提交答案" }}
              </button>
            </div>
          </div>

          <!-- 完成界面 -->
          <div v-else class="completion">
            <h2 class="complete-title">🎉 测评完成!</h2>
            <!-- <button class="analysis-btn">查看详细分析报告</button> -->
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import api from "@/api";

export default {
  data() {
    return {
      started: false,
      currentStep: 0,
      currentAnswer: "",
      chatHistory: [],
      isLoading: false,
      isSubmitting: false,
      questions: [
        "合同成立的基本要件有哪些？",
        "侵权责任的归责原则主要包含哪些？",
        "刑法中紧急避险的构成要件是什么？",
      ],
      userInfo: "",
      answerInfo: {},
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
    });
  },
  methods: {
    async startExam() {
      this.isLoading = true;
      await this.startQuestion();
      this.started = true;
      this.isLoading = false;
    },
    async startQuestion() {
      try {
        const result = await api.auth.start({
          person_id: this.userInfo.id,
        });
        console.log(result.data, "------");
        this.answerInfo = result.data;
        if (this.currentStep < result.data.round) {
          this.chatHistory.push({
            isUser: false,
            content: result.data.question,
          });
        }
      } catch (error) {
        console.error("请求失败:", error.message);
      }
    },
    formatContent(content) {
      console.log(content);
      return (
        content
          // 处理选择题格式
          .replace(/([A-D]\.)/g, '<div class="option">$1</div>')
          // 处理换行符
          .replace(/\n/g, "<br/>")
      );
    },
    async submitAnswer() {
      if (!this.currentAnswer.trim()) return;

      this.isSubmitting = true;
      // 添加用户回答
      this.chatHistory.push({
        isUser: true,
        content: this.currentAnswer,
      });

      await this.getAnswer();
    },
    async getAnswer() {
      try {
        const result = await api.auth.reply({
          person_id: this.userInfo.id,
          answer: this.currentAnswer,
          conversation_id: this.answerInfo.conversation_id,
          id: this.answerInfo.id,
          round: this.answerInfo.round,
        });
        console.log(result);
        this.currentStep++;
        this.currentAnswer = "";
        this.isSubmitting = false;
        if (this.currentStep <= result.data.round) {
          this.chatHistory.push({
            isUser: false,
            content: result.data.question,
          });
        }
        this.$nextTick(() => {
          const container = this.$el.querySelector(".dialog-scroll");
          container.scrollTop = container.scrollHeight;
        });
      } catch (error) {
        console.error("请求失败:", error.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
$primary-color: #3498db;
$secondary-color: #2ecc71;
$text-dark: #2c3e50;
$background-light: rgba(255, 255, 255, 0.95);

.chat-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  display: grid;
  place-items: center;
  padding: 1rem;
  box-sizing: border-box;

  .chat-card {
    background: $background-light;
    border-radius: 20px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
    // width: 100%;
    // min-width: 800px;
    width: 100%;
    min-height: 500px;
    padding: 2rem;
    backdrop-filter: blur(10px);
    box-sizing: border-box;

    @media (max-width: 767px) {
      border-radius: 20px;
      padding: 1rem;
      min-height: 90vh;
    }
  }
}

.start-section {
  text-align: center;
  padding: 2rem;

  .title-glow {
    color: $primary-color;
    text-shadow: 0 0 10px rgba($primary-color, 0.3);
    margin-bottom: 3rem;
  }
}

.neon-btn {
  position: relative;
  padding: 1.2rem 2.5rem;
  border: none;
  background: none;
  cursor: pointer;

  .neon-border {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border: 2px solid $primary-color;
    border-radius: 50px;
    box-shadow: 0 0 15px $primary-color, inset 0 0 15px $primary-color;
    animation: neon-pulse 1.5s infinite;
  }

  .neon-text {
    position: relative;
    z-index: 1;
    font-size: 1.5rem;
    color: $primary-color;
    text-shadow: 0 0 5px rgba($primary-color, 0.5);
  }

  &[disabled] {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.dialog-scroll {
  max-height: 400px;
  overflow-y: auto;
  padding: 1rem 0;

  @media (max-width: 767px) {
    max-height: 60vh;
  }
}

.chat-bubble {
  display: flex;
  margin: 1rem 0;
  opacity: 0;
  transform: translateY(20px);
  animation: chat-appear 0.3s forwards;

  .avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    background: $primary-color;
    color: white;
    flex-shrink: 0;
  }

  .bubble {
    max-width: 70%;
    padding: 1rem;
    border-radius: 15px;
    position: relative;
    // margin: 0 1rem;
    word-break: break-word;

    white-space: pre-line; // 新增：保留换行符
    line-height: 1.6; // 新增：增加行高

    // 新增：处理Markdown标题
    h3 {
      color: $primary-color;
      margin: 1rem 0;
      font-size: 1.1em;
      position: relative;
      padding-left: 1.5rem;

      &::before {
        content: "✧";
        position: absolute;
        left: 0;
      }
    }
    .options {
      margin: 0.8rem 0;
      padding-left: 1.5rem;

      div {
        margin: 0.5rem 0;
        &::before {
          content: "•";
          margin-right: 0.5rem;
          color: $secondary-color;
        }
      }
    }
  }

  &.user-bubble {
    flex-direction: row-reverse;

    .avatar {
      background: $secondary-color;
    }

    .bubble {
      background: $primary-color;
      color: white;
      border-bottom-right-radius: 3px;
    }

    .message-mark {
      right: -12px;
      color: $secondary-color;
    }
  }

  &:not(.user-bubble) {
    .bubble {
      background: #f0f4f8;
      border-bottom-left-radius: 3px;
    }

    .message-mark {
      left: -12px;
      color: $primary-color;
    }
  }

  .message-mark {
    position: absolute;
    top: -8px;
    font-size: 1.2em;
    filter: drop-shadow(0 2px 1px rgba(0, 0, 0, 0.1));
  }
}

.input-area {
  border-top: 2px solid #eee;
  padding: 1.5rem 0;

  .input-group {
    display: flex;
    gap: 1rem;
    @media (max-width: 767px) {
      flex-direction: column; // 改为垂直排列
      gap: 0.8rem; // 调整间距
    }

    textarea {
      flex: 1;
      padding: 0.8rem;
      border: 2px solid $primary-color;
      border-radius: 10px;
      resize: none;
      transition: 0.3s;

      &:focus {
        border-color: darken($primary-color, 10%);
        box-shadow: 0 0 10px rgba($primary-color, 0.3);
      }
    }
  }
}

.send-btn {
  @media (max-width: 767px) {
    width: 100%; // 全宽显示
    padding: 0.8rem; // 调整内边距
    font-size: 14px; // 缩小文字
  }
  background: $primary-color;
  color: white;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  transition: 0.3s;

  &:hover:not([disabled]) {
    background: darken($primary-color, 10%);
    transform: translateY(-2px);
  }

  &[disabled] {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.completion {
  text-align: center;
  padding: 2rem;

  .analysis-btn {
    background: linear-gradient(45deg, $primary-color, $secondary-color);
    color: white;
    padding: 1rem 2rem;
    border-radius: 30px;
    margin-top: 2rem;
    transition: 0.3s;

    &:hover {
      transform: scale(1.05);
    }
  }
}

@keyframes neon-pulse {
  0%,
  100% {
    opacity: 0.8;
  }
  50% {
    opacity: 0.4;
  }
}

@keyframes chat-appear {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>